var express = require('express');
var router = express.Router();
var User = require('../db/user.js');
var tools = require('../units/tools.js');
var article = require('../db/article');
var dynamic = require('../db/dynamic.js');
var Collection = require('../db/collections');


//专题收录文章
router.post("/doTopicFileAddAs", function (req, res, next) {
  // console.log(req.body);
  Collection.updateOne({ collectionid: req.body.cid }, { $addToSet: { listAid: req.body.aid } }, function (err) {
    if (err) { console.log(err); return; }
    res.send("收录成功");
  });
});

//获取已创建的专题
router.post("/getTopicFile", function (req, res, next) {
  Collection.find({ uid: req.cookies.userID }, function (err, data) {
    if (err) { console.log(err); return; }
    else {
      let collectionsList = [];
      if (data.length == 0) {
        res.send(collectionsList);
        // console.log(collectionsList);
      } else {
        for (let i = 0; i < data.length; i++) {
          collectionsList.push({
            cid: data[i].collectionid,
            filename: data[i].fileName,
            AsNum: data[i].listAid.length,
          });
        }
        res.send(collectionsList);
        // console.log(collectionsList);
      }
    }
  });
});

//新建专题
router.post("/addTopicFile", function (req, res, next) {
  User.findOne({ uid: req.cookies.userID }, function (err, data) {
    if (err) { console.log(err); return; }
    let CC = Collection({
      collectionid: req.cookies.userID + req.body.topicFileName,
      uid: req.cookies.userID,
      uname: data.uname,
      fileName: req.body.topicFileName,
      img: "",
    });
    CC.save(function (err, datas) {
      if (err) { res.send("创建失败，请重试"); return; }
      res.json({
        data: "专题创建成功！",
        cid: datas.collectionid,
        filename: req.body.topicFileName,
        AsNum: 0,
      });
    });
    // console.log(data);
  });
});

//消除未读评论
router.post('/removeCoMessage', function (req, res, next) {
  // console.log(req.body);
  if (!req.body.aid && !req.body.did) {
    article.updateMany({ uid: req.cookies.userID }, { "comment.$[].c_type": true }, function (err) {
      if (err) { console.log(err); }
      dynamic.updateMany({ uid: req.cookies.userID }, { "comment.$[].c_type": true }, function (err) {
        if (err) { console.log(err); }
        res.send("1");
      });
    });
  } else {
    if (!req.body.did) {
      article.updateOne({ a_id: req.body.aid }, { "comment.$[].c_type": true }, function (err) {
        if (err) { console.log(err); }
        res.json({
          aid: req.body.aid,
          did: "",
        });
      });
    } else {
      dynamic.updateOne({ d_id: req.body.did }, { "comment.$[].c_type": true }, function (err) {
        if (err) { console.log(err); }
        res.json({
          aid: "",
          did: req.body.did,
        });
      });
    }
  }
});

//获取未读评论
router.post('/getCoMessage', function (req, res, next) {
  async function getNoRead() {
    let AsMessage = [];
    let DyMessage = [];
    await article.find({ uid: req.cookies.userID }, function (err, AsCo) {
      if (err) { console.log(err); }
      for (let i = 0; i < AsCo.length; i++) {
        for (let j = 0; j < AsCo[i].comment.length; j++) {
          if (AsCo[i].comment[j].c_type == false) {
            AsMessage.push({
              aid: AsCo[i].a_id,
              cid: AsCo[i].comment[j].c_id,
              cname: AsCo[i].comment[j].c_name,
              chead: AsCo[i].comment[j].c_imgHead,
              ccontent: AsCo[i].comment[j].c_content,
              title: AsCo[i].title,
            });
          }
        }
      }
    });
    await dynamic.find({ uid: req.cookies.userID }, function (err, DyCo) {
      if (err) { console.log(err); }
      for (let i = 0; i < DyCo.length; i++) {
        for (let j = 0; j < DyCo[i].comment.length; j++) {
          if (DyCo[i].comment[j].c_type == false) {
            DyMessage.push({
              did: DyCo[i].d_id,
              cid: DyCo[i].comment[j].c_id,
              cname: DyCo[i].comment[j].c_name,
              chead: DyCo[i].comment[j].c_imgHead,
              ccontent: DyCo[i].comment[j].c_content,
            });
          }
        }
      }
    });
    return { AsMessage, DyMessage };
  };
  getNoRead().then(result => {
    // console.log(result);
    res.json({
      MsNum: result.AsMessage.length + result.DyMessage.length,
      MsAsList: result.AsMessage,
      MsDyList: result.DyMessage,
    });
  });
});


//关注(目标的粉丝列表+自己，自己的关注列表+目标)
router.post("/doFollows", function (req, res, next) {
  User.findOne({ uid: req.body.userid }, function (err, fList) {
    if (err) { console.log(err); }
    if (fList.fans.length != 0) {
      for (let i = 0; i < fList.fans.length; i++) {
        if (fList.fans[i] == req.cookies.userID) {
          res.send("你已经关注这位博主了哦！");
          return;
        }
      }
      User.updateOne({ uid: req.body.userid }, { $addToSet: { fans: req.cookies.userID } }, function (err) {
        if (err) { console.log(err); }
        User.updateOne({ uid: req.cookies.userID }, { $addToSet: { follows: req.body.userid } }, function (err) {
          if (err) { console.log(err); }
          res.send("关注成功！");
        });
      });
    } else {
      User.updateOne({ uid: req.body.userid }, { $addToSet: { fans: req.cookies.userID } }, function (err) {
        if (err) { console.log(err); }
        User.updateOne({ uid: req.cookies.userID }, { $addToSet: { follows: req.body.userid } }, function (err) {
          if (err) { console.log(err); }
          res.send("关注成功！");
        });
      });
    }
  })
});


router.post("/changeEMail", function (req, res, next) {
  let email = req.body.email;
  User.updateOne({ uid: req.cookies.userID }, { email: email }, function (err, data) {
    if (err) {
      console.log(err);
      return;
    } else {
      res.send("邮箱绑定成功！");
      // console.log(data);
    }
  });
});

router.post("/changePhone", function (req, res, next) {
  let account = req.body.phone;
  User.updateOne({ uid: req.cookies.userID }, { account: account }, function (err, data) {
    if (err) {
      console.log(err);
      return;
    } else {
      res.send("手机号修改成功！");
      // console.log(data);
    }
  });
});

router.post("/changePwd", function (req, res, next) {
  let password = req.body.password;
  User.updateOne({ uid: req.cookies.userID }, { pwd: password }, function (err, data) {
    if (err) {
      console.log(err);
      return;
    } else {
      res.send("密码修改成功！下次登录生效！");
      // console.log(data);
    }
  });
});

router.post("/imgHead", tools.multer().single("avatar"), function (req, res, next) {
  let imgHead = req.file.path.split("\\");
  let imgUrl = imgHead[1] + "/" + imgHead[2] + "/" + imgHead[3];
  console.log(req.body);
  User.updateOne({ uid: req.body.uid }, { img_head: imgUrl }, function (err) {
    if (err) {
      console.log(err);
      return;
    } else {
      res.send("头像修改成功!");
      // console.log(data);
    }
  });
});

router.post("/Personal", function (req, res, next) {
  // console.log(req.cookies.userID);
  User.findOne({ uid: req.cookies.userID }, function (err, data) {
    if (err) {
      console.log(err);
      return;
    } else {
      res.json({
        uid: data.uid,
        uname: data.uname,
        sex: data.sex,
        birth: data.birthday,
        uinfr: data.uinfr,
        img_head: data.img_head,
      })
    }
  })
});

router.post("/doPersonal", function (req, res, next) {
  let uname = req.body.name;//昵称
  let sex = req.body.sex;//性别
  let birthday = req.body.birth;//出生日期
  let uinfr = req.body.desc;//个人简介
  User.updateOne({ uid: req.cookies.userID }, { uname: uname, sex: sex, birthday: birthday, uinfr: uinfr }, function (err) {
    if (err) {
      console.log(err);
      return;
    } else {
      User.findOne({ uid: req.cookies.userID }, function (err, data) {
        if (err) { console.log(err); return; }
        article.updateMany({ uid: data.uid }, { uname: uname }, function (err) {
          if (err) { console.log(err); return; }
          res.send("修改成功！");
        })
      })
    }
  })
});

module.exports = router;
